package com.uum.blog.service.impl;

import com.uum.blog.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RedisServiceImpl implements RedisService {

    private final RedisTemplate redisTemplate;

    public final static String LIKE_REDIS_KEY = "like:commentID:";  //点赞key

    /**
     * 评论的ID作为Redis中的Key
     *
     * @param commentId
     * @return
     */
    @Override
    public String createLikeKey(Long commentId) {
        StringBuilder builder = new StringBuilder();
        builder.append(LIKE_REDIS_KEY);
        builder.append(commentId);
        return builder.toString();
    }


    @Override
    public Long saveLike(Long commentId, Long userId) {
        String key = createLikeKey(commentId);
        Long add = redisTemplate.opsForSet().add(key, userId);
        redisTemplate.expire(key, 1, TimeUnit.DAYS);
        return add;
    }

    @Override
    public Long countLike(Long commentId) {
        String key = createLikeKey(commentId);
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public Set listLike(Long commentId) {
        String key = createLikeKey(commentId);
        Set members = redisTemplate.opsForSet().members(key);
        return members;
    }

    @Override
    public Long deleteLike(Long commentId, Long userId) {
        String key = createLikeKey(commentId);
        return redisTemplate.opsForSet().remove(key, userId);
    }

    @Override
    public Boolean deleteComment(Long commentId) {
        String key = createLikeKey(commentId);
        return redisTemplate.delete(key);
    }

    @Override
    public Set<Map> listAllLike() {
        Set set = redisTemplate.keys(LIKE_REDIS_KEY + "*");
        Set<Map> result = new HashSet();
        for (Object obj: set) {
            Map map = new HashMap();
            Set members = redisTemplate.opsForSet().members(obj);
            map.put("commentId",obj);
            map.put("userId",members);
            result.add(map);
        }
        return result;
    }

    @Override
    public Long delAllLike() {
        Set delKeys = redisTemplate.keys(LIKE_REDIS_KEY + "*");
        Long effCount = redisTemplate.delete(delKeys);
        return effCount;
    }

}
